package com.threadpool.mythread.case01;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author 李李李
 * @2020/4/25 21:03
 *
 * Lock 锁定
 *
 */
public class Case02 {
    public static void main(String[] args) {
        Source source = new Source();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    source.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    source.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "C").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++){
                try {
                    source.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"D").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++){
                try {
                    source.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();
    }
}

/**
 * 资源类
 */
class Source02 {

    Lock lock = new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();

    private int number = 0;

    //相加方法
    public void increment() throws InterruptedException {
        lock.lock();
        try {
            if (number != 0) {
                condition1.await();
            }
            number++;
            //通知其他线程 我+1完毕
            condition1.signalAll();
            System.out.println(Thread.currentThread().getName() + "==>" + number);
        }finally {
            lock.unlock();
        }
    }

    //相减方法
    public void decrement() throws InterruptedException {
        lock.lock();
        try {
            if (number == 0) {
                condition1.wait();
            }
            number--;
            condition1.signalAll();
            //通知其他线程 我-1完毕
            System.out.println(Thread.currentThread().getName() + "==>" + number);
        }finally {
            lock.unlock();
        }
    }
}
